package views;

import dat065.app.R;
import util.DateChecker;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DateChoser extends Activity {
	private TextView mDateDisplay;
	private Button mPickDate;
	private Button dateDone;
	private int mYear;
	private int mMonth;
	private int mDay;
	
	private DateChecker dateChecker;

	static final int DATE_DIALOG_ID = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.datechoser);

		// capture our View elements
		mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
		mPickDate = (Button) findViewById(R.id.pickDate);
		dateDone = (Button) findViewById(R.id.dateDone);


		// add a click listener to the mPickDate button
		mPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		

		// add a click listener to the dateDone button
		dateDone.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//Should check the date then send the chosen date to TimeChoser view
			 /* 
				dateChecker = new DateChecker();
				if(DateChecker.checkDate(mYear, mMonth, mDay)){
					setResult(--- TO TimeChoser ---);
					finish();
				}
				else
					setResult(--- TO ErrorMSG ---);
					finish();
				*/	
				Intent outIntent = new Intent();
				outIntent.putExtra("year", mYear);
				outIntent.putExtra("month", mMonth);
				outIntent.putExtra("day", mDay);
				setResult(55, outIntent);
				finish();
			}
		});


	}
	// updates the date in the TextView
	private void updateDisplay() {
		mDateDisplay.setText(
				new StringBuilder()
				// Month is 0 based so add 1
				.append(mMonth + 1).append("-")
				.append(mDay).append("-")
				.append(mYear).append(" "));
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener =
		new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, 
				int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this,
					mDateSetListener,
					mYear, mMonth, mDay);
		}
		return null;
	}
}
